﻿using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Practices.Unity;
using MyAMS.WebServer.ActionFilter;
using MyAMS.WebServer.Infrastructure;

namespace MyAMS.WebServer
{
    /// <summary>
    /// 环境加载器
    /// </summary>
    public class EnvironmentLoader : IEnvironmentLoader
    {
        private readonly IUnityContainer unityContainer;

        /// <summary>
        /// 构造器
        /// </summary>
        /// <param name="unityContainer"></param>
        public EnvironmentLoader(IUnityContainer unityContainer)
        {
            this.unityContainer = unityContainer;
        }

        /// <summary>
        /// 获取或设置一个值, 改制指示当前实例是否已被加载
        /// </summary>
        public bool IsLoaded { get; protected set; }

        /// <summary>
        /// 加载
        /// </summary>
        public virtual void Load()
        {
            InitializeModelBinders();
            InitializeRoutes();
            InitializeControllerFactory();
            InitializeViewEngine();
            InitializeActionFilterRegistry();
            IsLoaded = true;
        }

        /// <summary>
        /// 卸载
        /// </summary>
        public virtual void UnLoad()
        {
            //TODO (5he11) 卸载逻辑
            IsLoaded = false;
        }

        /// <summary>
        /// 初始化路由表
        /// </summary>
        protected virtual void InitializeRoutes()
        {
            RouteTable.Routes.Clear();
            RouteTable.Routes.Add(new Route("{resource}.axd/{*pathInfo}", new StopRoutingHandler()));
            unityContainer.RegisterInstance(RouteTable.Routes);
        }

        /// <summary>
        /// 初始化模型绑定器
        /// </summary>
        protected virtual void InitializeModelBinders()
        {
            unityContainer.RegisterInstance(ModelBinders.Binders);
        }

        /// <summary>
        /// 初始化动作过滤器注册表
        /// </summary>
        protected virtual void InitializeActionFilterRegistry()
        {
            IActionFilterRegistry registry = unityContainer.Resolve<ActionFilterRegistry>();
            registry.Clear();
            unityContainer.RegisterInstance(registry);
        }

        /// <summary>
        /// 初始化控制器仓库
        /// </summary>
        protected virtual void InitializeControllerFactory()
        {
            unityContainer.RegisterType<IActionInvoker, CustomControllerActionInvoker>();
            ControllerBuilder.Current.SetControllerFactory(unityContainer.Resolve<ControllerFactory>());
        }

        /// <summary>
        /// 初始化试图引擎
        /// </summary>
        protected virtual void InitializeViewEngine()
        {
            ViewEngines.Engines.Clear();
            unityContainer.RegisterInstance(ViewEngines.Engines);
        }
    }
}
